/*
 * core_mqtt.h
 *
 *  Created on: 2021年9月22日
 *      Author: LF
 */

#include <string.h>
#include "main.h"
#include "transport.h"
#include "esp8266.h"

static unsigned char	s_sock_buf[256];
static int				s_rx_bytes;


/*  连接到mqtt服务器   */
int	transport_open(char *host, int port)
{
	return esp8266_sock_connect(host, port) ? -1 : 0;
}

/* 关闭连接    */
int	transort_close(void)
{
	return esp8266_sock_disconnect();
}

/*  发送报文给mqtt   */
int	transport_sendPacketBuffer(unsigned char *buf, int buflen)
{
	return esp8266_sock_send(buf, buflen);
}

/*  接收mqtt的报文   */
int	transport_getdata(unsigned char *buf,int count)
{
	int		rv = 0;

	if( !s_rx_bytes )
	{
		rv = esp8266_sock_recv(s_sock_buf, sizeof(s_sock_buf));
		if( !rv )
		{
			return 0;
		}

		s_rx_bytes = rv;
	}

	rv = (count > s_rx_bytes ? s_rx_bytes : count);

	memcpy(buf, s_sock_buf, rv);
	s_rx_bytes -= rv;

	if( s_rx_bytes > 0 )

		memmove(s_sock_buf, &s_sock_buf[rv], s_rx_bytes);

	return rv;
}

/*  清楚接受报文   */
void transport_clearBuf(void)
{
	memset(s_sock_buf, 0, sizeof(s_sock_buf));

	s_rx_bytes = 0;
}




